<template>
  <div
    class="dialog animated"
    :class="open? 'fadeIn':'fadeOut'"
    v-show="show"
    :style="{visibility: (visible?'visible':'hidden')}"
  >
    <div class="panel animated" :class="open? 'zoomIn':''">
      <div class="title">
        {{title}}
        <div class="close" @click="cancel()"></div>
      </div>
      <div>
        <div class="title_info">基本信息</div>
        <el-form :model="campusData" ref="campusData" label-width="240px">
          <el-form-item label="校区名称" :rules="[
      { required: true, message: ''}]">
            <el-input
              style="width:50%"
              clearable
              v-model="campusData.name"
              :disabled="isShow"
              placeholder="请输入校区名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所属机构"
            v-if="orgList.length>0"
            :rules="[
      { required: true, message: ''}]"
          >
            <el-select
              style="width:50%"
              v-model="campusData.orgId"
              :disabled="isShow"
              clearable
              placeholder="请选择机构"
            >
              <el-option
                v-for="item in orgList"
                :key="item.orgId"
                :label="item.orgName"
                :value="item.orgId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="校区电话">
            <el-input
              style="width:50%"
              :disabled="isShow"
              clearable
              v-model="campusData.tel"
              maxlength="12"
              placeholder="请输入校区电话，如：020-12345678"
            ></el-input>
          </el-form-item>
          <el-form-item label="校区logo">
            <el-upload
              class="avatar-uploader"
              style="margin-top:0.36rem;"
              :action="uploadUrl"
              :show-file-list="false"
              :disabled="isShow"
              :data="uploadData"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <img @click="clickPic(false)" v-if="imgUrl_44" :src="imgUrl_44" class="avatar" />
              <img
                @click="clickPic(false)"
                :disabled="isShow"
                src="../../../assets/img/system_set/def_logo1.jpg"
                v-else
              />
              <div
                slot="tip"
                class="el-upload__tip"
                style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;"
              >44x44</div>
            </el-upload>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :disabled="isShow"
              :data="uploadData"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <img @click="clickPic(true)" v-if="imgUrl_202" :src="imgUrl_202" class="avatar" />
              <img
                @click="clickPic(true)"
                :disabled="isShow"
                src="../../../assets/img/system_set/def_logo2.jpg"
                v-else
              />
              <div
                slot="tip"
                class="el-upload__tip"
                style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;padding-left:0.7rem"
              >210x82</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="校区所在地区" :rules="[
      { required: true, message: ''}]">
            <el-cascader
            :key="isResouceShow"
              style="width:50%"
              clearable
              :disabled="isShow"
              :props="defaultProps"
              :options="citys"
              v-model="campusData.regionAddress"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="校区详细地址">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow"
              maxlength="50"
              v-model="campusData.address"
              placeholder="请输入校区详细地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="校长姓名" :rules="[
      { required: true, message: ''}]">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow || isEnableUser"
              v-model="campusData.contactsName"
              placeholder="请输入校长姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" :rules="[
      { required: true, message: ''}]">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow || isEnableUser"
              v-model="campusData.contactsTel"
              maxlength="11"
              @input="getNum"
              placeholder="请输入校长手机号，并为该校区管理员账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="合作类型" :rules="[
      { required: true, message: ''}]">
            <el-select
              style="width:50%"
              :disabled="isShow || isEnableUser"
              v-model="campusData.cooperationMode"
              @change="orgModeChange"
              clearable
              placeholder="请选择合作类型"
            >
              <el-option
                v-for="item in cooperationModeList"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="服务期限"
            v-if="campusData.cooperationMode != 2"
            :rules="[
      { required: true, message: ''}]"
          >
            <el-row style="width:50%">
              <el-col :span="10">
                <el-date-picker
                  type="date"
                  :disabled="isShow || isEnableUser"
                  placeholder="开始日期"
                  v-model="campusData.serveStartTime"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
              <el-col style="text-align: center;" :span="3">-</el-col>
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  :disabled="isShow || isEnableUser"
                  placeholder="结束日期"
                  v-model="campusData.serveEndTime"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow"
              maxlength="50"
              v-model="campusData.remark"
              placeholder="请输入补充说明信息"
            ></el-input>
          </el-form-item>
          <el-form-item label="校区编号">
            <el-input
              style="width:50%"
              clearable
              maxlength="6"
              :disabled="isShow"
              v-model="campusData.kindId"
              placeholder="HD****"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="line_from"></div>
        <div class="title_info">设备授权</div>
         <el-form label-width="240px">
        	<el-form-item label="授权设备数量" :rules="[
      { required: true, message: ''}]">
        		<el-input-number
        		  ref="authCount"
        		  size="small"
        		  controls-position="right"
        		  class="newclassroomNumber"
        		  style="width:20%;"
        		  v-model="campusData.authCount"
        		  :disabled="isShow"
        		  :min="1"
        		  :max="99999"
        		></el-input-number>
        		<span >&nbsp;&nbsp;台</span>
        	</el-form-item>
        	<el-form-item  label="授权设备使用: " v-if="!isAdd">
        		&nbsp;&nbsp;{{campusData.usedAuth == null ?'0':campusData.usedAuth}}/{{campusData.authCount}} <el-button type="primary" :disabled="isShow" style="margin-left: 0.2rem;" @click="clearAuth()">清空授权</el-button>
        	</el-form-item>
        </el-form>
        <div class="title_info">家校通信息</div>
        <div class="label">授权后赋能：</div>
        <div class="enabling">通过将校区【微信公众号】开放平台账号管理授权给【威校管理平台】，校区可获得：
        	1、获得校区的【家校通】，校区家长可在【校区微信公众号】访问家校通，获知孩子在校学习情况；
        	2、家长报课后，关注【校区微信公众号】，可获得“上课、续费“等消息通知；
        </div>
        <div class="label">授权步骤：</div>
        <div class="step">
        	<div class="step_text" style="padding-top: 0.14rem;line-height: 0.18rem;">
        		<div>1</div>
        		<div>配置</div>
        		<div>威校域名</div>
        	</div>
        	<div class="step_line"></div>
        	<div class="step_text">
        		<div>2</div>
        		<div>扫码授权</div>
        	</div>
        	<div class="step_line"></div>
        	<div class="step_text">
        		<div>3</div>
        		<div>配置APPID</div>
        	</div>
        	<div class="step_line"></div>
        	<div class="step_text">
        		<div>4</div>
        		<div>授权成功</div>
        	</div>
        </div>
        <div class="step_detail" @click="openStepDetail()">查看详细操作步骤</div>

        <el-form label-width="240px">
        	<el-form-item label="校区公众号APPID">
        		<el-input style="width:50%" :disabled="isShow" clearable  maxlength="50" v-model="campusData.appId" placeholder="请输入校区公众号ID"></el-input>
        		<!--&nbsp;
        		<span class="appId_explain" @click="gotoHtml()">如何获取公众号ID?</span>-->
        	</el-form-item>
        	<el-form-item v-if="campusData.appId" label="微信校验文件信息" :rules="[{ required: true, message: ''}]">
        		<el-input style="width:50%" clearable  :disabled="isShow" maxlength="50" v-model="campusData.wechatCheckFileMsg" placeholder="请输入微信校验文件信息"></el-input>
        	</el-form-item>
        </el-form>
        <!-- <div class="title_explain">家校通是与家长沟通的版块,可通过配置下面内容,获取家校通链接,挂接至校区微信公号中</div>
        <el-form label-width="240px">
          <el-form-item label="家校通logo">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :disabled="isShow"
              :data="uploadData"
              :on-success="handleAvatarSuccess_school"
              :before-upload="beforeAvatarUpload_school"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <img v-if="imgUrl_school" :src="imgUrl_school" class="avatar" />
              <img :disabled="isShow"  style="width:1rem;height:1rem; display: block;object-fit: cover;" src="../../../assets/img/system_set/def_logo1.jpg" v-else />
              <div
                slot="tip"
                class="el-upload__tip"
                style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;"z
              >100x100</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="校区公众号ID">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow"
              maxlength="50"
              v-model="campusData.appId"
              placeholder="请输入校区公众号ID"
            ></el-input>
            <span class="appId_explain" @click="gotoHtml()">如何获取公众号ID?</span>
          </el-form-item>
          <el-form-item v-if="campusData.appId" label="微信校验文件信息" :rules="[
      { required: true, message: ''}]">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow"

              maxlength="50"
              v-model="campusData.wechatCheckFileMsg"
              placeholder="请输入微信校验文件信息"
            ></el-input>
          </el-form-item>
        </el-form> -->
      </div>
      <div class="btn_div" v-if="!isShow">
        <div class="btn_sure" @click="sure()">确 认</div>
        <div class="btn_cancel" @click="cancel()">取 消</div>
      </div>
    </div>
  </div>
</template>

<script>
import citys from "@/../static/citys.json";
var vm;

export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      isAdd: true,
      isShow: false,
      isEnable: false,
      isEnableUser: false,
      title: "",
      uploadData: {
        content: "campuslogo"
      },
      citys: [],
      orgList: [],
      isTwo: false,
      imgUrl_44: "",
      isResouceShow:1,
      imgUrl_202: "",
      imgUrl_school: "",
      campusData: {},
      cooperationModeList: [],
      uploadUrl: window.config.baseUrl + "file/upload",
      orgModeList: [],
      defaultProps: {
        label: "label",
        value: "value",
        children: "children"
      },
      headers: {
        // 'Content-Type': 'multipart/form-data',
        token: tool.getItem(lsKey.token)
      }
    };
  },
  methods: {
    // 清空授权
    clearAuth(){
      api.clearDeviceAuth({campusId:vm.campusData.campusId}).then(function(data) {
        if (data.resultCode == 2000) {
          vm.$message({
            message: "清空授权成功",
            type: "success"
          });
          vm.$emit("callback", "添加成功");
           vm.campusData.usedAuth = 0;
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    openStepDetail(){
      window.open("res/doc/指引微信公众号授权文档.pdf", "_blank");
    },
    gotoHtml() {
      window.open(window.config.baseUrl + "static/威校微信相关.pdf", "_blank");
    },
    clickPic(isTwo) {
      vm.isTwo = isTwo;
    },
    getNum(e) {
      vm.campusData.contactsTel = e.replace(/[^\d]/g, "");
    },
    orgModeChange: function(val) {
      if (val == 2) {
        vm.campusData.serveStartTime = "1946-02-14";
        vm.campusData.serveEndTime = "2999-12-30";
      } else {
        vm.campusData.serveStartTime = "";
        vm.campusData.serveEndTime = "";
      }
    },
    uploadError: function(response, file) {
      console.log("上传文件失败response" + response);
    },

    handleAvatarSuccess_school(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，" + res.data.result);
      } else {
        this.imgUrl_school = res.data.url;
      }
    },
    beforeAvatarUpload_school(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传logo图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 2MB!");
        return false;
      }
      let fontSize = "44x44";
      const isSize = new Promise(function(resolve, reject) {
        let width = fontSize.split("x")[0];
        let height = fontSize.split("x")[1];
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
          let value = image.width == width && image.height == height;
          value ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          tool.message({
            showClose: true,
            message: "上传logo图片尺寸不符合，应为" + fontSize,
            type: "warning"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },

    handleAvatarSuccess(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，" + res.data.result);
      } else {
        if (!vm.isTwo) {
          this.imgUrl_44 = res.data.url;
        } else {
          this.imgUrl_202 = res.data.url;
        }
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传logo图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 2MB!");
        return false;
      }
      let fontSize;
      if (!vm.isTwo) {
        fontSize = "44x44";
      } else {
        fontSize = "210x82";
      }

      const isSize = new Promise(function(resolve, reject) {
        let width = fontSize.split("x")[0];
        let height = fontSize.split("x")[1];
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
          let value = image.width == width && image.height == height;
          value ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          tool.message({
            showClose: true,
            message: "上传logo图片尺寸不符合，应为" + fontSize,
            type: "warning"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 11);
      let user = tool.getItem(lsKey.user, true); //得到当前用户信息
      //获取数据字典
      let dicdata = tool.getItem(lsKey.dict, true);
      vm.cooperationModeList = dicdata["cooperation_mode"];
      vm.citys = citys;
      // console.log(citys);
      if (data.campusId != null) {
        vm.isAdd = false;
        vm.title = "编辑校区";
        vm.isEnable = true;
        if (data.isShow) {
          vm.isShow = true;
          vm.title = "查看校区";
        }
        let campusData = data;
        campusData.regionAddress = [data.province, data.city, data.area];
        if (campusData.icon &&  campusData.icon != "") {
          vm.imgUrl_44 = campusData.icon.split(",")[0];
          vm.imgUrl_202 = campusData.icon.split(",")[1];
        } else {
          vm.imgUrl_44 = "";
          vm.imgUrl_202 = "";
        }
        vm.imgUrl_school = campusData.eduToHomeLogo;
        ++vm.isResouceShow;
        vm.campusData = campusData;
        if (user.roleMode == 2) {
          // vm.campusData.orgId = user.orgId;
          vm.isEnableUser = true;
        }
        console.log(vm.campusData);
      } else {
        vm.isAdd = true;
        vm.title = "新增校区";
        ++vm.isResouceShow;
        vm.campusData = {
          orgId: "",
          name: "",
          tel: "",
          icon: "",
          regionAddress: [],
          province: "",
          city: "",
          area: "",
          address: "",
          contactsName: "",
          contactsTel: "",
          cooperationMode: "",
          serveStartTime: "",
          kindId:"",
          serveEndTime: "",
          remark: "",
          appId: "",
          authCount:"",
          eduToHomeLogo: "",
          wechatCheckFileMsg: ""
        };
        if (user.roleMode == 1) {
          vm.campusData.orgId = user.orgId;
        } else if (user.roleMode == 0) {
          api.orgList().then(function(data) {
            if (data.result == "操作成功") {
              vm.orgList = data.list;
            }
          });
        } else {
          this.$message.error("该账号无权限新增校区");
          vm.cancel();
        }
      }
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      vm.imgUrl = "";
      // vm.$refs.regionAddress.sValue=[];
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.isAdd = true;
        vm.isShow = false;
        vm.isEnable = false;
        vm.isEnableUser = false;
        vm.isTwo = false;
        vm.imgUrl_44 = "";
        vm.imgUrl_202 = "";
      }, 500);
    },
    sure: function() {
      console.log(vm.campusData.name);
      if (vm.campusData.name == "") {
        this.$message.warning("校区名称不能为空");
        return;
      }
      if (!tool.judge("campusname", vm.campusData.name)) {
        this.$message.warning("请输入有效的校区名称");
        return;
      }
      if (vm.campusData.orgId == "") {
        this.$message.warning("所属机构不能为空");
        return;
      }
      if (
        (vm.imgUrl_44 == "" && vm.imgUrl_202 != "") ||
        (vm.imgUrl_44 != "" && vm.imgUrl_202 == "")
      ) {
        this.$message.warning("如需上传校区logo，则必须上传两种分辨率的logo");
        return;
      }
      if (vm.campusData.contactsName == "") {
        this.$message.warning("校长负责人不能为空");
        return;
      }
      if (!tool.judge("name", vm.campusData.contactsName)) {
        this.$message.warning("请输入有效的校长负责人");
        return;
      }
      if (vm.campusData.contactsTel == "") {
        this.$message.warning("校长手机不能为空");
        return;
      }
      if (!tool.judge("phone", vm.campusData.contactsTel)) {
        this.$message.warning("手机号不匹配!");
        return;
      }
      if (vm.campusData.cooperationMode == "") {
        this.$message.warning("合作模式不能为空");
        return;
      }
      if (vm.campusData.serveStartTime == "") {
        this.$message.warning("服务开始时间不能为空");
        return;
      }
      if (vm.campusData.serveEndTime == "") {
        this.$message.warning("服务结束时间不能为空");
        return;
      }
      if(vm.campusData.appId != "" && vm.campusData.wechatCheckFileMsg == ""){
        this.$message.warning("请输入微信校验文件信息");
        return;
      }
      if (
        vm.campusData.regionAddress.length > 0 &&
        vm.campusData.regionAddress[0] != null
      ) {
        vm.campusData.province = vm.campusData.regionAddress[0];
        vm.campusData.city = vm.campusData.regionAddress[1];
        vm.campusData.area = vm.campusData.regionAddress[2];
      } else {
        this.$message.warning("请选择校区所在的省市区");
        return;
      }
      if (vm.campusData.serveStartTime instanceof Date) {
        vm.campusData.serveStartTime = tool.DateToString(
          vm.campusData.serveStartTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.campusData.serveEndTime instanceof Date) {
        vm.campusData.serveEndTime = tool.DateToString(
          vm.campusData.serveEndTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.imgUrl_44 != "") {
        vm.campusData.icon = vm.imgUrl_44 + "," + vm.imgUrl_202;
      }
      vm.campusData._wait = "";
      if (vm.isAdd) {
        api.campusAdd(vm.campusData).then(function(data) {
          console.log(data);
          if (data.resultCode == 2000) {
            vm.$message({
              message: "添加成功",
              type: "success"
            });
            vm.$emit("callback", "添加成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      } else {
        // paras.userId = vm.accountData.userId;
        api.campusUpdate(vm.campusData).then(function(data) {
          console.log(data);
          if (data.resultCode == 2000) {
            vm.$message({
              message: "修改成功",
              type: "success"
            });
            vm.$emit("callback", "修改成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      }
    }
  },
  created: function() {
    vm = this;
  }
};
</script>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped>
.appId_explain {
  color: #409eff;
  font-size: 0.14rem;
  text-decoration: underline;
  cursor: pointer;
}
.line_from {
  height: 1px;
  margin: 0.24rem 0.18rem 0.18rem 0.18rem;
  background-color: #f3f6fc;
}
.title_info {
  padding-left: 0.3rem;
  font-size: 0.16rem;
  color: #666666;
}
.title_explain {
  padding-left: 0.3rem;
  font-size: 0.14rem;
  color: #999999;
  margin-top: 0.1rem;
  margin-bottom: 0.2rem;
}
.label {
  padding-left: 1rem;
  font-size: 0.16rem;
  margin: 0.2rem 0 0.1rem 0;
  /*outline: 1px solid red;*/
}
.enabling {
	padding-left: 2rem;
	 /*outline: 1px solid red;*/
	 font-size: 0.14rem;
  	white-space: pre-line;
  	line-height: 0.26rem;
}
.step {
	overflow: hidden;
	padding-left: 2rem;
}
.step_text {
	float: left;
	text-align: center;
	font-size: 0.14rem;
	padding-top: 0.2rem;
	width: 0.9rem;
	height: 0.9rem;
	border-radius: 0.45rem;
	border: 0.01rem solid #409eff;
	line-height: 0.22rem;
	background: #f9f9f9;
}
.step_line {
	float: left;
	width: 0.4rem;
	height: 0.01rem;
	background: #409eff;
	margin: 0.44rem 0.06rem 0 0.06rem;
}
.step_detail {
	color: #409eff;
  	font-size: 0.14rem;
  	text-decoration: underline;
  	cursor: pointer;
  	margin: 0.2rem 0 0.3rem 0;
  	padding-left: 4rem;
}
.btn_div {
  padding: 0 0 0.3rem 0;
}
.panel {
  width: 10rem;
  padding-bottom: 0.2rem;
}
.ruleForm {
  padding-left: 0.5rem;
}
.el-radio-group {
  line-height: inherit;
}
.tree {
  padding: 0.1rem 0.5rem;
  /* max-height: 5.4rem; */
}
.el-col {
  border-radius: 4px;
}
.bg-purple {
  background: #d3dce6;
}
.grid-content {
  line-height: 0.5rem;
  text-align: center;
}
.avatar-uploader {
  float: left;
  margin-left: 0.2rem;
}
.avatar-uploader .el-upload {
  border: 1px dashed #453374;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  display: block;
  object-fit: cover;
}
</style>
